﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace EzDesk.DevHelper.HtmlToAspx
{
    public class FormPresenter
    {
        IHtmlToAspxView _view = null;

        FormModel _model;

        private bool _isSourceFolderReady = false;
        private bool _isOutputFolderReady = false;

        private string _rootFolder;

        private string rootFolder{
            get
            {
                if (string.IsNullOrEmpty(_rootFolder))
                {
                    _rootFolder = getEzDeskRootPath();
                }
                return _rootFolder;
            }
        }


        private bool hasFoundRootFolder
        {
            get
            {
                return rootFolder != string.Empty;
            }
        }

        
        public FormPresenter(IHtmlToAspxView view)
        {
            this._view = view;
            this._rootFolder = getEzDeskRootPath();

            initializeView();
        }

        private void setViewModel()
        {
            _view.SetFormModel(_model);
        }

        private void initializeView()
        {
            _model = new FormModel()
            {
               SourceHtmlFileFolder = "",
               SourceHtmlFileList = new List<string>(),
               OutputFolder = "",
               canSycnCssAndJs =  false,
               canSyncHtmlToAspx = false,
               isAutoCheckOut = true,
            };
            setViewModel();
            _view.DisplayStatus("初始化完成", false);

            autoFindSourceFolder();
            autoOutputFolder();
        }

        /// <summary>
        /// 寻找EzDesk项目跟文件夹,通过EzDesk-dev.sln文件定位
        /// </summary>
        /// <returns>找不到返回empty</returns>
        private string getEzDeskRootPath()
        {
            string fileName = "EzDesk-Dev.sln";
            string pathStr = Directory.GetCurrentDirectory();
            do
            {
                string fullFileName = string.Format(
                    "{0}\\{1}",
                    pathStr,
                    fileName
                    );
                if (File.Exists(fullFileName))
                {
                    // 找到文件
                    break;
                }

                DirectoryInfo parentInfo = Directory.GetParent(pathStr);
                if (parentInfo != null)
                {
                    pathStr = parentInfo.FullName;
                }
                else
                {
                    pathStr = string.Empty;
                    break;
                }
            } while (true);

            return pathStr;
        }

        private void autoOutputFolder()
        {
            // 从程序当前文件夹开始向上寻找EzDesk-Dev.sln

            const string outputRelPath = "Clients\\EzDesk.Clients.DesktopWeb\\Views";

            if (hasFoundRootFolder)
            {
                string outputFolder = Path.Combine(rootFolder, outputRelPath);

                if (!Directory.Exists(outputFolder))
                {
                    _isOutputFolderReady = false;
                    throw new DirectoryNotFoundException(outputFolder);
                }

                _isOutputFolderReady = true;
                _model.OutputFolder = outputFolder;
                setViewModel();

                getReadyForConvert();
            }
            else
            {
                _view.DisplayStatus("无法定位EzDesk-Dev根文件夹", true);
            }
        }

        private void autoFindSourceFolder()
        {
            const string sourceRelPath = "DevHelper\\EzDesk.DevHelper.HtmlDev\\HtmlDev\\html";

            if (hasFoundRootFolder)
            {
                string sourceFolder = Path.Combine(rootFolder, sourceRelPath);
                if (!Directory.Exists(sourceFolder))
                {
                    _isSourceFolderReady = false;
                    throw new DirectoryNotFoundException(sourceFolder);
                }

                _model.SourceHtmlFileFolder = sourceFolder;
                _model.SourceHtmlFileList = 
                    Directory.GetFiles(sourceFolder)
                        .Select(Path.GetFileName)
                        .ToList();
                _isSourceFolderReady = true;
                setViewModel();

                getReadyForConvert();
            }
            else
            {
                _view.DisplayStatus("无法定位EzDesk-Dev根文件夹", true);
            }
        }

        private void getReadyForConvert()
        {
            if (hasFoundRootFolder && _isOutputFolderReady && _isSourceFolderReady)
            {
                _model.canSycnCssAndJs = true;
                _model.canSyncHtmlToAspx = true;
            }
            else
            {
                _model.canSycnCssAndJs = false;
                _model.canSyncHtmlToAspx = false;
            }

            setViewModel();
        }



        private void prepareForConvertorCheckout(EzTfsConverter convertor)
        {
            const int MAX_CHECKOUT_ONETIME = 25; //一次checkout这么多文件

            if (_model.isAutoCheckOut)
            {
                // 尝试checkOut
                var sourceFiles = convertor.SourceFiles();
                

                int i = 0;
                var outputFileList = new StringBuilder();
                foreach (var sourceFile in sourceFiles)
                {
                    string destFile = convertor.GetDestFile(sourceFile);
                    string systemFilePath = getSystemPath(destFile);
                    
                    outputFileList.Append(systemFilePath);
                    outputFileList.Append(" ");
                    i++;

                    if (i == MAX_CHECKOUT_ONETIME || sourceFiles.IndexOf(sourceFile) == sourceFiles.Count - 1)
                    {
                        i = 0;
                        tryCheckOut(outputFileList.ToString());
                        outputFileList.Clear();
                    }
                }
            }
        }
        
        /// <summary>
        /// 尝试Check一个文件
        /// </summary>
        /// <param name="systemFilePath"></param>
        private void tryCheckOut(string systemFilePath)
        {
            _view.DisplayStatus(
                string.Format("尝试自动CheckOut文件: {0}", systemFilePath)
                , false
                );

            string cmdStr = "tf_checkout.cmd";
            string cmdParameter = systemFilePath;

            TfCmd.ExecuteCmd(string.Format("{0} {1}",
                    cmdStr,
                    cmdParameter
                ));

            _view.DisplayStatus(
                string.Format("完成自动CheckOut文件: {0} 完成", systemFilePath)
                , false
                );
        }

        private string getSystemPath(string targetFileName)
        {
            const string systemFilePathBase = "\"$/EzDesk-Dev/{0}\""; ;
            targetFileName = targetFileName.Substring(rootFolder.Length + 1).Replace("\\", "/");
            string result = string.Format(systemFilePathBase, targetFileName);
            return result;
        }






        public void GetReadyForConvert()
        {
            getReadyForConvert();
        }

        public void AutoOutputFolder()
        {
            try
            {
                this.autoOutputFolder();
            }
            catch (DirectoryNotFoundException ex)
            {
                _view.DisplayStatus("无法找到输出文件夹： " + ex.Message, true);
            }
        }

        public void AutoFindSourceFolder()
        {
            try
            {
                this.autoOutputFolder();
            }
            catch (DirectoryNotFoundException ex)
            {
                _view.DisplayStatus("无法找到输入文件夹： " + ex.Message, true);
            }

        }

        public void ConvertHtmlToAspx(string fileName)
        {
            try
            {
                string htmlFileName = Path.Combine(_model.SourceHtmlFileFolder, fileName);
                string outputFolder = _model.OutputFolder;

                var convertor = new HtmlConvertor(htmlFileName, outputFolder);

                prepareForConvertorCheckout(convertor);
                convertor.Convert();

                // 转换成功
                _view.DisplayStatus("转换成功： " + fileName, false);
            }
            catch (UnauthorizedAccessException ex)
            {
                _view.DisplayStatus("自动CheckOut失败，大概你需要手动Check Out目标文件！\n" + ex.Message, true);
            }
        }

        

        public void SyncCssAndJs()
        {
            try
            {
                var convertor = new EzCssAndJsConverter(rootFolder);

                prepareForConvertorCheckout(convertor);

                convertor.Convert();

                _view.DisplayStatus("同步完成", false);
            }
            catch (UnauthorizedAccessException ex)
            {
                _view.DisplayStatus("大概你需要先Check Out目标文件！\n" + ex.Message, true);
            }
        }



        public void SetAutoCheckOut(bool isAutoChecked)
        {
            _model.isAutoCheckOut = isAutoChecked;
            setViewModel();
        }

    }
}
